﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DAL.Category
{
    /// <summary>
    /// CategoryRepository
    /// </summary>
    public class CategoryRepository
    {
        private ImsContext _context = null;

        public CategoryRepository()
        {
            _context = new ImsContext();
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<BO.Category> GetAll()
        {
            //   var repository = new Repository<BO.Product>(_adapter);
            //  return repository.GetAll();

            var query = from p in _context.Categories
                        select p;

            return query.ToList();
        }

        /// <summary>
        /// Inserts the specified product.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <returns></returns>
        public BO.Category Insert(BO.Category category)
        {
            BO.Category entity = null;
            if (category != null)
            {
                category.CreateDate = DateTime.Now;
                category.Active = true;
                entity = _context.Categories.Add(category);
                _context.SaveChanges();
            }
            return entity;
        }

        /// <summary>
        /// Updates the specified product.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <returns></returns>
        public int Update(BO.Category category)
        {
            int result = -1;
            if (category != null && category.CategoryId.HasValue)
            {
                category.CreateDate = DateTime.Now;
                category.Active = true;
                var entity = _context.Categories.FirstOrDefault(x => x.CategoryId == category.CategoryId);
                if (entity != null)
                {
                    entity.Name = category.Name;
                    entity.Description = category.Description;
                    entity.UpdateDate = DateTime.Now;
                }
                result = _context.SaveChanges();
            }
            return result;
        }

        /// <summary>
        /// Gets the by id.
        /// </summary>
        /// <param name="productId">The product id.</param>
        /// <returns></returns>
        public BO.Category GetById(int? categoryId)
        {
            return _context.Categories.FirstOrDefault(x => x.CategoryId == categoryId);
        }

        public int Delete(int? categoryId)
        {
            var entity = _context.Categories.FirstOrDefault(x => x.CategoryId == categoryId);
            if (entity != null)
            {
                _context.Categories.Remove(entity);
                _context.SaveChanges();
                return 1;
            }
            return -1;
        }
    }
}